#include "threadPool.h"

void cleanmutex(void *arg)
{
    threadPool_t *threadPool = (threadPool_t *)arg;
    pthread_mutex_unlock(&threadPool->taskQueue.mutex);
}
int recvn(int sockfd, void *buf, int length)
{
    int total = 0;
    char *p = (char *)buf;
    while (total < length)
    {
        ssize_t sret = recv(sockfd, p + total, length - total, 0);
        total += sret;
    }
    return total;
}

int recvComd(int netfd, char *pathname)
{
    char comdname[100];
    int length;
    recvn(netfd, &length, sizeof(length));
    recvn(netfd, comdname, length);

    if (length == 0)
    {
        return -1;
    }
    char buf[1024];
    recvn(netfd, &length, sizeof(length));
    recvn(netfd, buf, length);
    for (int i = 0; i < (int)strlen(buf); ++i)
    {
        if (buf[i] == '\n')
        {
            buf[i] = '\0';
        }
    }

    if (strcmp(comdname, "cd") == 0)
    {
        netDriveCd(pathname, buf, netfd);
    }
    else if (strcmp(comdname, "ls") == 0)
    {
        netDriveLs(pathname, netfd);
    }
    else if (strcmp(comdname, "puts") == 0)
    {
        netDrivePuts(pathname, buf, netfd);
    }
    else if (strcmp(comdname, "gets") == 0)
    {
        netDriveGets(pathname, buf, netfd);
    }
    else if (strcmp(comdname, "remove") == 0)
    {
        netDriveRemove(pathname, buf, netfd);
    }
    else if (strcmp(comdname, "pwd") == 0)
    {
        netDrivePwd(pathname, netfd);
    }
    else if (strcmp(comdname, "mkdir") == 0)
    {
        netDriveMkdir(pathname, buf, netfd);
    }
    else if (strcmp(comdname, "rmdir") == 0)
    {
        netDriveRmdir(pathname, buf, netfd);
    }
    return 0;
}

void *threadFunc(void *arg)
{
    threadPool_t *threadPool = (threadPool_t *)arg;
    while (1)
    {
        int netfd;

        pthread_mutex_lock(&threadPool->taskQueue.mutex);
        while (threadPool->exitFlag == 0 && threadPool->taskQueue.queueSize == 0)
        {
            pthread_cond_wait(&threadPool->taskQueue.cond, &threadPool->taskQueue.mutex);
        }

        if (threadPool->exitFlag != 0)
        {
            printf("child thread is going to exit!\n");
            pthread_mutex_unlock(&threadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        printf("worker thread get task!\n");
        netfd = threadPool->taskQueue.pFront->netfd;
        taskDeQueue(&threadPool->taskQueue);
        pthread_mutex_unlock(&threadPool->taskQueue.mutex);
         
        userCheck(netfd);
        char pathname[1024];
        strcpy(pathname, ".");
        while (1)
        {
            int ret = recvComd(netfd, pathname);
            if (ret == -1)
            {
                break;
            }
        }
        close(netfd);
    }
}

int makeWorker(threadPool_t *threadPool)
{
    for (int i = 0; i < threadPool->threadnum; ++i)
    {
        pthread_create(&threadPool->tidArr[i], NULL, threadFunc, threadPool);
    }
    return 0;
}
